<template>
  <div>
    <el-tag
      v-for="(item, idx) in tags"
      :key="idx"
      closable
      :disable-transitions="false"
      @close="handleClose(idx)"
    >
      {{item}}
    </el-tag>
    <el-button
      v-if="mode === INPUT_STATUS.NORMAL"
      class="button-new-tag"
      size="small"
      icon="el-icon-plus"
      :disabled="tags.length >= 5"
      @click="handleToAdd"
    >
      新增
    </el-button>
    <el-input
      class="input-new-tag"
      v-if="mode === INPUT_STATUS.PREPARED"
      v-model.trim="inputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleAdd"
      @blur="handleAdd"
      maxlength="10"
    >
    </el-input>
  </div>
</template>

<script>
const INPUT_STATUS = {
  NORMAL: 'NORMAL',
  PREPARED: 'PREPARED'
}

export default {
  name: "StandardTagInput",
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 当前模式
      mode: INPUT_STATUS.NORMAL,
      // 标准标签列表
      tags: [],
      // 正常或异常项输入的值
      inputValue: '',
    }
  },
  computed: {
    INPUT_STATUS() {
      return INPUT_STATUS
    }
  },
  watch: {
    '$props.value': {
      handler(value) {
        this.tags = value ? value.split(',') : []
      },
      immediate: true
    },
    tags(value) {
      this.$emit('input', value.join(','))
    }
  },
  methods: {
    handleClose(idx) {
      this.tags.splice(idx, 1)
    },
    handleToAdd() {
      this.inputValue = ''
      this.mode = this.INPUT_STATUS.PREPARED
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    handleAdd() {
      this.tags = [].concat(this.tags, this.inputValue ? this.inputValue.split(',') : [])
      this.mode = this.INPUT_STATUS.NORMAL
      this.inputValue = ''
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
